@page "/children"
@inject ILocalStorageService LocalStorage
@inject ILogService LogService
@inject NavigationManager Navigation

<PageTitle>孩子档案管理</PageTitle>

<div>
    <Title Level="2">孩子档案管理</Title>
    
    <div style="margin: 16px 0;">
        <Button Type="@ButtonType.Primary" Icon="user-add" OnClick="AddChild">
            添加孩子
        </Button>
        <Button Icon="reload" OnClick="RefreshData" Style="margin-left: 8px;">
            刷新
        </Button>
    </div>
    
    @if (loading)
    {
        <Spin Spinning="true" Size="large">
            <div style="height: 200px;"></div>
        </Spin>
    }
    else if (children?.Any() == true)
    {
        <Table DataSource="children" 
               TItem="ChildProfile" 
               Bordered="true" 
               Size="TableSize.Middle"
               PageSize="10"
               Responsive>
            <PropertyColumn Property="c => c.Name" Title="姓名" />
            <PropertyColumn Property="c => c.Grade" Title="年级" />
            <PropertyColumn Property="c => c.Semester" Title="学期" />
            <PropertyColumn Property="c => c.Stage" Title="阶段" />
            <PropertyColumn Property="c => c.CreateDate" Title="创建时间" Format="yyyy-MM-dd" />
            <ActionColumn Title="操作">
                <Space>
                    <SpaceItem>
                        <Button Type="@ButtonType.Link" Size="small" OnClick="() => EditChild(context)">
                            编辑
                        </Button>
                    </SpaceItem>
                    <SpaceItem>
                        <Button Type="@ButtonType.Link" Size="small" OnClick="() => ViewExams(context)">
                            试卷
                        </Button>
                    </SpaceItem>
                    <SpaceItem>
                        <Popconfirm Title="确定要删除此孩子档案吗？" 
                                    OnConfirm="() => DeleteChild(context)"
                                    OkText="确定" 
                                    CancelText="取消">
                            <Button Type="@ButtonType.Link" Danger Size="small">
                                删除
                            </Button>
                        </Popconfirm>
                    </SpaceItem>
                </Space>
            </ActionColumn>
        </Table>
    }
    else
    {
        <Empty Description="@("暂无孩子档案")">
            <Button Type="@ButtonType.Primary" Icon="user-add" OnClick="AddChild">
                添加第一个孩子档案
            </Button>
        </Empty>
    }
</div>

<!-- 添加/编辑孩子对话框 -->
<Modal Title="@(editingChild?.Id == 0 ? "添加孩子" : "编辑孩子")"
       Visible="showModal"
       OnOk="SaveChild"
       OnCancel="CloseModal"
       OkText="@("保存")"
       CancelText="@("取消")"
       ConfirmLoading="saving">
    <Form Model="editingChild" LabelCol="new ColLayoutParam { Span = 6 }" WrapperCol="new ColLayoutParam { Span = 18 }">
        <FormItem Label="姓名">
            <Input @bind-Value="editingChild!.Name" Placeholder="请输入孩子姓名" />
        </FormItem>
        <FormItem Label="年级">
            <Select @bind-Value="editingChild!.Grade" 
                    Placeholder="请选择年级"
                    TItemValue="int"
                    TItem="int">
                <SelectOptions>
                    @for (int i = 1; i <= 6; i++)
                    {
                        <SelectOption Value="i" Label="@($"{i}年级")" TItemValue="int" TItem="int" />
                    }
                </SelectOptions>
            </Select>
        </FormItem>
        <FormItem Label="学期">
            <RadioGroup @bind-Value="editingChild!.Semester">
                <Radio RadioButton Value="@("上学期")">上学期</Radio>
                <Radio RadioButton Value="@("下学期")">下学期</Radio>
            </RadioGroup>
        </FormItem>
        <FormItem Label="阶段">
            <RadioGroup @bind-Value="editingChild!.Stage">
                <Radio RadioButton Value="@("前期")">前期</Radio>
                <Radio RadioButton Value="@("期中")">期中</Radio>
                <Radio RadioButton Value="@("期末")">期末</Radio>
            </RadioGroup>
        </FormItem>
    </Form>
</Modal>

@code {
    private List<ChildProfile>? children;
    private bool loading = true;
    private bool showModal = false;
    private bool saving = false;
    private ChildProfile editingChild = new();
    
    protected override async Task OnInitializedAsync()
    {
        await LoadChildren();
    }
    
    private async Task LoadChildren()
    {
        try
        {
            loading = true;
            children = await LocalStorage.GetChildrenAsync();
            await LogService.LogInfoAsync("加载孩子档案列表", "Children");
        }
        catch (Exception ex)
        {
            await LogService.LogErrorAsync($"加载孩子档案失败: {ex.Message}", "Children");
        }
        finally
        {
            loading = false;
            StateHasChanged();
        }
    }
    
    private void AddChild()
    {
        editingChild = new ChildProfile();
        showModal = true;
    }
    
    private void EditChild(ChildProfile child)
    {
        editingChild = new ChildProfile
        {
            Id = child.Id,
            Name = child.Name,
            Grade = child.Grade,
            Semester = child.Semester,
            Stage = child.Stage,
            CreateDate = child.CreateDate
        };
        showModal = true;
    }
    
    private async Task SaveChild()
    {
        if (string.IsNullOrWhiteSpace(editingChild.Name))
        {
            // TODO: 显示错误消息
            return;
        }
        
        try
        {
            saving = true;
            var savedId = await LocalStorage.SaveChildAsync(editingChild);
            await LogService.LogInfoAsync($"保存孩子档案: {editingChild.Name}", "Children");
            
            showModal = false;
            await LoadChildren();
        }
        catch (Exception ex)
        {
            await LogService.LogErrorAsync($"保存孩子档案失败: {ex.Message}", "Children");
        }
        finally
        {
            saving = false;
        }
    }
    
    private async Task DeleteChild(ChildProfile child)
    {
        try
        {
            var success = await LocalStorage.DeleteChildAsync(child.Id);
            if (success)
            {
                await LogService.LogInfoAsync($"删除孩子档案: {child.Name}", "Children");
                await LoadChildren();
            }
        }
        catch (Exception ex)
        {
            await LogService.LogErrorAsync($"删除孩子档案失败: {ex.Message}", "Children");
        }
    }
    
    private void ViewExams(ChildProfile child)
    {
        Navigation.NavigateTo($"/exams?childId={child.Id}");
    }
    
    private void CloseModal()
    {
        showModal = false;
        editingChild = new();
    }
    
    private async Task RefreshData()
    {
        await LoadChildren();
    }
} 